<?php


namespace App\Http\Controllers\Admin;

use App\Http\Common\BaseController;

use App\Models\Banner;
use App\Models\BannerType;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class BannerController  extends BaseController
{
    /**
     * 获取轮播图type
     * @param Request $request
     * @return mixed
     */
    public function selBannerType(){
        return $this->returnJson(self::SUCCESS,'成功',BannerType::get());
    }

    /**
     * get所有轮播图
     * @param Request $request
     * @return mixed
     */
    public function selBanners(Request $request){
        $type_id = $request->input('type_id',0);

        if ($type_id == 0){
            return  $this->returnJson(self::FIELD_ERROR,'请输入轮播图类型');
        }

        return $this->returnJson(self::SUCCESS,'成功',Banner::where('banner_type_id','=',$type_id)->get());
    }

    /**
     * 添加轮播图
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function  creatBanners(Request $request){
        $file = $request->file('file');
        $type_id = $request->input('type_id', 0);
        $user_id =$request->userId;

        if ($type_id == 0){
            return  $this->returnJson(self::FIELD_ERROR,'请输入轮播图类型');
        }
        //获取文件后缀
        $suffix = $file->getClientOriginalExtension();

        //判断文件后缀
        $rule = ['jpg', 'png', 'gif','jpeg'];
        if (!in_array($suffix, $rule)) return $this->returnJson(BaseController::FIELD_ERROR, '上传的文件格式必需为jpg/png/gif');

        //判断文件大小
        $fileSize = $file->getSize();
        if ($fileSize > 10 * 1024 * 1024){
            return $this->returnJson(BaseController::FIELD_ERROR, '上传的文件必须在10m以内');
        }
        $fileUrl = md5(time() . $file->getClientOriginalName()) . '.' . $suffix;
        //创建启动事务
        DB::beginTransaction();
        try {
            if (!$filename = $this->uploadOss('wdad/admin_banner/' . $type_id , $fileUrl, $file->getRealPath())){
                return $this->returnJson(self::ERROR,'失败');
            }
            Banner::insert([
                'banner_type_id' => $type_id,
                'url' => $filename['oss-request-url'],
            ]);

            $type_name = BannerType::where('id', '=', $type_id)->pluck('name')[0];
            $content = $this->mkNoticeContent($user_id,'',$type_name ,2);
            $this->creatNotice(5,$user_id,$content);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->returnJson(self::DATA_NOTFOUND,'服务器错误，请稍后从试',$e);
        }

        return  $this->returnJson(self::SUCCESS,'成功');
    }

    /**
     * 修改轮播图
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function  updateBanners(Request $request){
        $file = $request->file('file');
        $id = $request->input('id', 0);

        $user_id =$request->userId;

        if ($id == 0){
            return  $this->returnJson(self::FIELD_ERROR,'请输入轮播图ID');
        }
        if (!$banner = Banner::where('id',$id)->get()[0]){
            return  $this->returnJson(self::FIELD_ERROR,'轮播图ID不存在');
        }
        $type_id  = $banner['banner_type_id'] ;
        $url  = $banner['url'] ;


        //获取文件后缀
        $suffix = $file->getClientOriginalExtension();

        //判断文件后缀
        $rule = ['jpg', 'png', 'gif','jpeg'];
        if (!in_array($suffix, $rule)) return $this->returnJson(BaseController::FIELD_ERROR, '上传的文件格式必需为jpg/png/gif');

        //判断文件大小
        $fileSize = $file->getSize();
        if ($fileSize > 10 * 1024 * 1024){
            return $this->returnJson(BaseController::FIELD_ERROR, '上传的文件必须在10m以内');
        }
        $fileUrl = md5(time() . $file->getClientOriginalName()) . '.' . $suffix;
        //创建启动事务
        DB::beginTransaction();
        try {

            //获取需要截取的内容
            if (strstr($url, 'http://')){
                $prefix = "http://" . env('BUCKET') . '.' . env('ENDPOINT') . '/';
            }else{
                $prefix = "https://" . env('BUCKET') . '.' . env('ENDPOINT') . '/';
            }
            $exist = substr($url, strlen($prefix));

            //删除文件
            if (!$this->deleteOss($exist)){
                return $this->returnJson(BsaeController::ERROR, '文件删除失败成功');
            }

            if (!$filename = $this->uploadOss('wdad/admin_banner/' . $type_id, $fileUrl, $file->getRealPath())){
                return $this->returnJson(self::ERROR,'失败');
            }

            Banner::where('id',$id)->update([
                    'url' => $filename['oss-request-url'],
            ]);

            $type_name = BannerType::where('id', '=', $type_id)->pluck('name')[0];
            $content = $this->mkNoticeContent($user_id,'',$type_name ,4);
            $this->creatNotice(5,$user_id,$content);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->returnJson(self::DATA_NOTFOUND,'服务器错误，请稍后从试',$e);
        }

        return  $this->returnJson(self::SUCCESS,'成功');
    }
    /**
     * 删除轮播图
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function  delBanners(Request $request){
        $id = $request->input('id', 0);
        $user_id =$request->userId;

        if ($id == 0){
            return  $this->returnJson(self::FIELD_ERROR,'请输入轮播图ID');
        }
        if (!$banner = Banner::where('id',$id)->get()[0]){
            return  $this->returnJson(self::FIELD_ERROR,'轮播图ID不存在');
        }
        $type_id  = $banner['banner_type_id'] ;
        //创建启动事务
        DB::beginTransaction();
        try {
            Banner::where('id',$id)->delete();

            $type_name = BannerType::where('id', '=', $type_id)->pluck('name')[0];
            $content = $this->mkNoticeContent($user_id,'',$type_name ,3);
            $this->creatNotice(5,$user_id,$content);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->returnJson(self::DATA_NOTFOUND,'服务器错误，请稍后从试',$e);
        }

        return  $this->returnJson(self::SUCCESS,'成功');
    }

}
